<template>
  <div class="order-management">
    <!-- 搜索区域 -->
    <el-card class="box-card operation-container" shadow="never">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="订单ID">
          <el-input 
            v-model="searchForm.orderId" 
            placeholder="输入订单ID"
            clearable
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input 
            v-model="searchForm.userId" 
            placeholder="输入用户ID"
            clearable
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input 
            v-model="searchForm.username" 
            placeholder="输入用户名称"
            clearable
            @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="选择状态" 
            clearable
            @change="onSearch"
          >
            <el-option label="未确认" :value="0"></el-option>
            <el-option label="已确认" :value="1"></el-option>
            <el-option label="已付款" :value="2"></el-option>
            <el-option label="已发货" :value="3"></el-option>
            <el-option label="已取消" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch" :loading="searchLoading">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card table-container" shadow="never" v-loading="tableLoading">
      <div v-if="tableData.length === 0 && !tableLoading" class="empty-data">
        <el-empty description="暂无订单数据">
          <el-button type="primary" @click="getAllOrders">重新加载</el-button>
        </el-empty>
      </div>
      
      <el-table v-else :data="tableData" style="width: 100%" border>
        <el-table-column prop="orderId" label="订单ID" width="120" align="center">
          <template #default="scope">
            <a href="#" class="id-link" @click="viewOrderDetail(scope.row)">
              {{ scope.row.orderId }}
            </a>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="下单时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="userId" label="用户ID" width="100" align="center">
          <template #default="scope">
            {{ scope.row.userId }}
          </template>
        </el-table-column>
        
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="center">
          <template #default="scope">
            <span class="amount">¥{{ formatAmount(scope.row.totalAmount) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="address" label="收货地址" width="200" align="center">
          <template #default="scope">
            <el-tooltip :content="scope.row.address" placement="top" :disabled="!scope.row.address">
              <span class="address-text">{{ scope.row.address || '暂无地址' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="商品详情" width="150" align="center">
          <template #default="scope">
            <el-button 
              type="info" 
              size="small"
              @click="viewOrderItems(scope.row)"
            >
              查看商品({{ scope.row.orderItems?.length || 0 }})
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 2" 
              type="success" 
              size="small"
              @click="handleShip(scope.row)"
            >
              发货
            </el-button>
            <el-button 
              v-if="scope.row.status < 3" 
              type="warning" 
              size="small"
              @click="handleCancel(scope.row)"
            >
              取消订单
            </el-button>
            <!-- <el-button 
              type="danger" 
              size="small"
              :icon="Delete" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container" v-if="totalCount > 0">
        <span>第{{ currentPage }}页/共{{ totalCount }}条记录</span>
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :total="totalCount"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="ml-auto"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="70%">
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">{{ currentOrder.orderId }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ formatAmount(currentOrder.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="订单备注" :span="2">{{ currentOrder.orderDetail || '无备注' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentOrder.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentOrder.updateTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog v-model="itemsDialogVisible" title="订单商品详情" width="60%">
      <el-table :data="currentOrderItems" border>
        <el-table-column prop="orderDetailId" label="详情ID" width="100" align="center"></el-table-column>
        <el-table-column prop="productId" label="商品ID" width="100" align="center"></el-table-column>
        <el-table-column prop="price" label="单价" width="120" align="center">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" align="center"></el-table-column>
        <el-table-column label="小计" width="120" align="center">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.price * scope.row.quantity) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import request from '../../util/request.js'

// 响应式数据
const searchForm = ref({
  orderId: '',
  userId: '',
  username: '',
  status: null
})

const tableData = ref([])
const tableLoading = ref(false)
const searchLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const itemsDialogVisible = ref(false)
const currentOrder = ref(null)
const currentOrderItems = ref([])

// API 基础路径
const API_BASE = '/admin/order'

// 订单状态映射 - 根据接口文档更新
const statusMap = {
  0: '未确认',
  1: '已确认', 
  2: '已付款',
  3: '已发货',
  4: '已取消'  // 注意：接口文档中是4，不是5
}

// 获取状态对应的标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning', 
    2: 'primary',
    3: 'success',
    4: 'danger'  // 更新为4
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || '未知状态'
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

// 格式化日期时间 - 处理数组格式的时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  
  // 如果是数组格式 [2025, 5, 21, 15, 52, 5]
  if (Array.isArray(datetime)) {
    const [year, month, day, hour, minute, second] = datetime
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
  }
  
  // 如果是字符串格式
  return new Date(datetime).toLocaleString('zh-CN')
}

// 获取所有订单 - 使用后端分页
const getAllOrders = async () => {
  try {
    tableLoading.value = true
    console.log('正在请求:', `${API_BASE}/all`)
    
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchForm.value.orderId) {
      params.orderId = parseInt(searchForm.value.orderId)
    }
    if (searchForm.value.userId) {
      params.userId = parseInt(searchForm.value.userId)
    }
    if (searchForm.value.status !== null && searchForm.value.status !== '') {
      params.status = searchForm.value.status
    }
    
    const response = await request.get(`${API_BASE}/all`, { params })
    console.log('订单列表响应:', response.data)
    
    // 根据接口文档，后端返回 code: 1 表示成功
    if (response.data.code === 1) {
      const pageResult = response.data.data
      tableData.value = pageResult.records || []
      totalCount.value = pageResult.total || 0
      
      console.log('获取到订单数据:', tableData.value)
      
      if (tableData.value.length === 0) {
        ElMessage.info('暂无订单数据')
      } else {
        ElMessage.success(`成功获取 ${tableData.value.length} 条订单数据`)
      }
    } else {
      ElMessage.error(`获取订单列表失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    
    if (error.response) {
      const status = error.response.status
      const message = error.response.data?.msg || error.response.statusText
      ElMessage.error(`请求失败 (${status}): ${message}`)
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
  } finally {
    tableLoading.value = false
  }
}

// 根据用户名搜索订单
const searchByUsername = async (username) => {
  try {
    searchLoading.value = true
    console.log('搜索请求:', `${API_BASE}/username?userName=${username}`)
    
    const response = await request.get(`${API_BASE}/username`, {
      params: { userName: username }
    })
    
    console.log('搜索响应:', response.data)
    
    if (response.data.code === 1) {
      // 用户名搜索返回的是数组，不是分页格式
      tableData.value = response.data.data || []
      totalCount.value = tableData.value.length
      currentPage.value = 1  // 重置页码
      
      if (tableData.value.length === 0) {
        ElMessage.info('未找到相关订单')
      } else {
        ElMessage.success(`找到 ${tableData.value.length} 条相关订单`)
      }
    } else {
      ElMessage.error(`搜索失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    searchLoading.value = false
  }
}

// 搜索功能
const onSearch = () => {
  currentPage.value = 1  // 搜索时重置页码
  
  if (searchForm.value.username.trim()) {
    // 如果有用户名，使用专门的用户名搜索接口
    searchByUsername(searchForm.value.username.trim())
  } else {
    // 否则使用分页查询接口
    getAllOrders()
  }
}

// 重置搜索
const onReset = () => {
  searchForm.value = {
    orderId: '',
    userId: '',
    username: '',
    status: null
  }
  currentPage.value = 1
  getAllOrders()
}

// 发货操作
const handleShip = async (row) => {
  try {
    console.log('发货请求:', { orderId: row.orderId, status: 3 })
    
    const response = await request.put(`${API_BASE}/updateStatus`, {
      orderId: row.orderId,
      status: 3
    })
    
    console.log('发货响应:', response.data)
    
    if (response.data.code === 1) {
      ElMessage.success(`订单 #${row.orderId} 已标记为发货`)
      // 更新本地数据
      const index = tableData.value.findIndex(item => item.orderId === row.orderId)
      if (index !== -1) {
        tableData.value[index].status = 3
      }
    } else {
      ElMessage.error(`发货操作失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('发货操作失败:', error)
    ElMessage.error('发货操作失败')
  }
}

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 #${row.orderId} 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    console.log('取消订单请求:', { orderId: row.orderId, status: 4 })
    
    const response = await request.put(`${API_BASE}/updateStatus`, {
      orderId: row.orderId,
      status: 4  // 根据接口文档，取消状态是4
    })
    
    console.log('取消订单响应:', response.data)
    
    if (response.data.code === 1) {
      ElMessage.success('订单已取消')
      // 更新本地数据
      const index = tableData.value.findIndex(item => item.orderId === row.orderId)
      if (index !== -1) {
        tableData.value[index].status = 4
      }
    } else {
      ElMessage.error(`取消订单失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
    }
  }
}

/* // 删除订单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 #${row.orderId} 吗？此操作不可恢复！`,
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
      }
    )
    
    console.log('删除订单请求:', row.orderId)
    
    const response = await request.delete(`${API_BASE}/delete/${row.orderId}`)
    
    console.log('删除订单响应:', response.data)
    
    if (response.data.code === 1) {
      ElMessage.success('删除成功')
      // 重新加载当前页数据
      getAllOrders()
    } else {
      ElMessage.error(`删除失败: ${response.data.msg || '未知错误'}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
} */

// 查看订单详情
const viewOrderDetail = (row) => {
  currentOrder.value = row
  dialogVisible.value = true
}

// 查看商品详情
const viewOrderItems = (row) => {
  currentOrderItems.value = row.orderItems || []
  itemsDialogVisible.value = true
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getAllOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getAllOrders()
}

// 初始化加载数据
onMounted(() => {
  console.log('组件挂载，开始加载订单数据...')
  getAllOrders()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.operation-container.el-card,
.table-container.el-card {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 0;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.ml-auto {
  margin-left: auto;
}

.id-link {
  color: #e6a23c;
  text-decoration: underline;
  cursor: pointer;
}

.id-link:hover {
  color: #ebb563;
}

.amount {
  font-weight: bold;
  color: #e6a23c;
}

.address-text {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty-data {
  text-align: center;
  padding: 40px;
}
</style>
